<template>
  <view class="flex-col page">
    <view class="flex-col group" style="flex-shrink: 0">
      <view class="justify-center group_1" style="flex-shrink: 0">
        <image
          src="https://codefun-proj-user-res-1256085488.cos.ap-guangzhou.myqcloud.com/61ab188e1f655f0011bbaece/61e7d9270c0e3200129ec72c/16425844615651288038.png"
          class="image_1"
        />
        <text class="text">{{
          order_status == 0
            ? "待支付"
            : order_status == 1
            ? "等待技师确认"
            : order_status == 2
            ? "待服务"
            : order_status == 3
            ? "服务进行中"
            : order_status == 4
            ? "已完成订单待评价"
            : order_status == 5
            ? "已评价订单"
            : order_status == 8
            ? "已出发"
            : order_status == 9
            ? "已到达"
            : order_status == 7
            ? "已退款订单"
            : "已取消订单"
        }}</text>
      </view>
    </view>
    <view class="flex-col group_2" style="flex-shrink: 0">
      <view class="justify-between group_3">
        <view
          class="left-text-wrapper flex-col view"
          :class="{ 'select-active': teps == 3 }"
        >
          <text class="text_2">技师出发</text>
        </view>
        <view
          class="left-text-wrapper flex-col"
          :class="{ 'select-active': teps == 5 }"
        >
          <text class="text_2">开始服务</text>
        </view>
      </view>
      <view class="center-group justify-center view_2">
        <!-- <view class="flex-col items-center section_1">
					<view class="flex-col items-center text-wrapper">
					</view>
				</view> -->
        <view class="section_3 view_3" :class="{ 'select-active': teps == 1 }">
          <view class="flex-col items-center text-wrapper" v-show="teps == 1">
          </view>
        </view>
        <view class="section_2"> </view>
        <view class="section_3 view_3" :class="{ 'select-active': teps == 2 }">
          <view class="flex-col items-center text-wrapper" v-show="teps == 2">
          </view>
        </view>
        <image
          src="https://project-user-resource-1256085488.cos.ap-guangzhou.myqcloud.com/61ab188e1f655f0011bbaece/61e7d9270c0e3200129ec72c/16425844976579604976.png"
          class="image_2"
        />
        <view class="section_3" :class="{ 'select-active': teps == 4 }">
          <view class="flex-col items-center text-wrapper" v-show="teps == 4">
          </view>
        </view>
        <image
          src="https://project-user-resource-1256085488.cos.ap-guangzhou.myqcloud.com/61ab188e1f655f0011bbaece/61e7d9270c0e3200129ec72c/16425844976577539029.png"
          class="image_3"
        />
        <view class="section_3" :class="{ 'select-active': teps == 6 }">
          <view class="flex-col items-center text-wrapper" v-show="teps == 6">
          </view>
        </view>
      </view>
      <view class="justify-between steps-text">
        <view class="flex-row">
          <text class="text_6" :class="{ 'text-active': teps == 1 }">下单</text>
          <text class="text_7" :class="{ 'text-active': teps == 2 }">接单</text>
        </view>
        <view class="flex-row group_6">
          <text :class="{ 'text-active': teps == 4 }">技师到达</text>
        </view>
        <view class="flex-row group_6">
          <text class="text_9" :class="{ 'text-active': teps == 6 }"
            >服务完成</text
          >
        </view>
      </view>
    </view>
    <view class="flex-col group_7" style="flex-shrink: 0">
      <view class="justify-between group_8" style="flex-shrink: 0">
        <!-- <view class="flex-col items-center text-wrapper_1" @click="hide">
					<text>取消订单</text>
				</view> -->
        <view
          class="flex-col items-center text-wrapper_2"
          @tap.stop="onMultClick(show)"
          v-if="order_status == 0"
        >
          <text>立即支付</text>
        </view>

        <view
          class="flex-col items-center text-wrapper_3"
          @click="completeOrder(order_sn)"
          v-if="order_status == 3"
        >
          <text>提前完成</text>
        </view>

        <view
          class="flex-col items-center text-wrapper_3"
          @click="addtime(1)"
          v-if="order_status == 3"
        >
          <text>立即加钟</text>
        </view>
        <view
          class="flex-col items-center text-wrapper_3"
          @click="addtime(0)"
          v-if="order_status == 2 || order_status == 3"
        >
          <text>升级服务</text>
        </view>
      </view>
      <view class="flex-col section_4" style="flex-shrink: 0">
        <view class="flex-col" style="flex-shrink: 0">
          <view class="flex-row group_10">
            <view class="section_5"> </view>
            <text class="text_12">服务项目</text>
          </view>
          <view class="flex-row group_11" style="flex-shrink: 0">
            <view
              class="flex-col section_6"
              :style="{ backgroundImage: `url(${cover})` }"
            >
              <view class="flex-col text-wrapper_3" v-if="false">
                <text class="text_13">环境疲劳·激活能量</text>
              </view>
            </view>
            <view class="flex-col group_12">
              <text class="text_14">{{ name }}</text>
              <view class="group_13">
                <text class="text_15">￥</text>
                <text class="text_16">{{ pay_money }}</text>
              </view>
              <view class="center-group flex-row view_6">
                <image
                  src="https://codefun-proj-user-res-1256085488.cos.ap-guangzhou.myqcloud.com/61ab188e1f655f0011bbaece/61e7d9270c0e3200129ec72c/16425844603803770493.png"
                  class="image_4"
                />
                <text class="text_17">时长{{ duration }}分钟</text>
              </view>
              <text class="text_18">服务时间：{{ appointment_time }}</text>
            </view>
          </view>
        </view>
        <view class="flex-col group_14">
          <view class="justify-between">
            <text class="text_19">出行交通费用</text>
            <text class="text_20">￥{{ fare }}</text>
          </view>
          <view class="justify-between group_16">
            <text class="text_21">优惠券</text>
            <text class="text_22">-￥{{ discount }}</text>
          </view>
          <view class="justify-between" style="padding-top: 10rpx">
            <text class="text_19">加钟次数</text>
            <text class="text_20">{{ clock_num }}次</text>
          </view>

          <view class="justify-between group_16">
            <text class="text_21">加钟时长</text>
            <text class="text_22">{{ clock_duration }} 分钟</text>
          </view>
        </view>
        <view class="flex-col group_17">
          <view class="divider"> </view>
          <view class="group_18 justify-between">
            <view class="flex-row">
              <image :src="avatar" class="image_5" />
              <view class="flex-col group_20">
                <view class="flex-row">
                  <text class="text_23">{{ realname }}</text>
                  <view class="flex-col items-end group_22">
                    <view class="flex-col items-center text-wrapper_4">
                      <text>认证</text>
                    </view>
                    <image
                      src="https://project-user-resource-1256085488.cos.ap-guangzhou.myqcloud.com/61ab188e1f655f0011bbaece/61e7d9270c0e3200129ec72c/16425844795953096993.png"
                      class="image_6"
                    />
                  </view>
                </view>
                <view class="flex-row group_23">
                  <!--  -->
                  <u-icon
                    v-for="(sitem, sindex) in parseInt(praise)"
                    :key="sindex"
                    name="star-fill"
                    size="12"
                    color="rgba(243, 151, 53, 1)"
                  ></u-icon>

                  <text class="text_25">好评{{ praise }}分</text>
                </view>
              </view>
            </view>
            <view
              class="flex-col items-center text-wrapper_5"
              @click="call"
              v-if="[1, 2, 8, 9].indexOf(order_status) >= 0"
            >
              <text>联系技师</text>
            </view>
          </view>
          <view class="divider"> </view>
        </view>
        <view class="group_18 flex-col">
          <view class="flex-row">
            <text class="text_27">{{ user_realname }}</text>
            <text class="text_28">{{ user_mobile }}</text>
          </view>
          <text class="text_29">{{ address }}</text>
        </view>
        <view class="flex-col">
          <view class="divider"> </view>
          <view class="group_18 flex-col">
            <view class="justify-between">
              <text class="text_30">订单总额</text>
              <view class="group_27">
                <text class="text_31">￥</text>
                <text class="text_32">{{ total_money }}</text>
              </view>
            </view>
            <view class="justify-between group_28">
              <text class="text_33">实付款(含车费)</text>
              <text class="text_34">￥{{ pay_money }}</text>
            </view>
            <view class="justify-between group_29">
              <text class="text_35">车费</text>
              <text class="text_36">￥{{ fare }}</text>
            </view>
            <view class="justify-between group_29">
              <text class="text_35">车程</text>
              <text class="text_36">{{ trip.distance }} 公里</text>
            </view>

            <view class="justify-between group_29" v-if="order_status == 7">
              <text class="text_35 refundTxt">已退款</text>
              <text class="text_36 refundTxt">{{ refund }} 元</text>
            </view>
          </view>
        </view>
        <view class="flex-col">
          <view class="divider"> </view>
          <view class="group_18 flex-col">
            <view class="justify-between">
              <text class="text_30">订单信息</text>
            </view>
            <view class="justify-between group_28">
              <text class="text_33">订单编号</text>
              <text class="text_34">{{ order_sn }}</text>
            </view>
            <view class="justify-between group_29">
              <text class="text_35">下单时间</text>
              <text class="text_36">{{ create_time }}</text>
            </view>
          </view>
        </view>
        <view class="divider"> </view>
        <view class="flex-col items-center text-wrapper_6" @click="calltel">
          <text>联系客服</text>
        </view>
      </view>
    </view>

    <u-popup
      :show="popupshow"
      mode="center"
      @close="popupshow = false"
      :round="10"
    >
      <view style="padding: 50rpx 60rpx">
        <view style="text-align: center"> 选择您要加钟的项目 </view>
        <view style="text-align: center; color: #797979; font-size: 25rpx">
          选择加钟项目确认支付后，服务时间加长
        </view>
        <view class="" v-for="(item, index) in lockData" :key="index">
          <view
            class="flex"
            :class="selectIndex == index ? 'selectIndexcurre' : 'selectIndex'"
            @click="selectTime(index, item)"
          >
            <view>
              <image
                src="../../../static/images/time.png"
                mode="widthFix"
                style="width: 40rpx"
              >
              </image>
            </view>
            <view class="">
              <span style="font-size: 28rpx">时长(分钟)：</span>
              <span style="color: #1f1e1f; font-weight: bold">{{
                item.duration
              }}</span>
            </view>
            <view class="" style="padding-left: 30rpx">
              <span style="font-size: 28rpx">费用(元)：</span>
              <span style="color: #fa3534; font-weight: bold">{{
                item.price
              }}</span>
            </view>
          </view>
        </view>
        <!--支付方式start-->

        <u-radio-group
          v-model="payType"
          placement="column"
          style="display: block; margin-top: 20rpx"
        >
          <view
            class="justify-between section_10"
            :class="!index ? 'section_9' : ''"
            v-for="(item, index) in payList"
            :key="index"
            style="flex-shrink: 0"
          >
            <view class="flex-row" style="flex-shrink: 0">
              <image
                :src="
                  index === 0
                    ? 'https://codefun-proj-user-res-1256085488.cos.ap-guangzhou.myqcloud.com/61ab188e1f655f0011bbaece/61e7d9270c0e3200129ec72c/16425844612123080341.png'
                    : index === 1
                    ? 'https://codefun-proj-user-res-1256085488.cos.ap-guangzhou.myqcloud.com/61ab188e1f655f0011bbaece/61e7d9270c0e3200129ec72c/16425844612334581390.png'
                    : 'https://codefun-proj-user-res-1256085488.cos.ap-guangzhou.myqcloud.com/61ab188e1f655f0011bbaece/61e7d9270c0e3200129ec72c/16425844612491703390.png'
                "
                class="image_5"
              />
              <text class="margin_left">{{ item.name }}</text>
              <text
                class=""
                v-if="!index"
                style="color: #797979; font-size: 22rpx"
                >（余额：￥{{ Number(user.balance) }}）</text
              >
              <!-- （余额：￥{{ Number(user.balance) }}） -->
            </view>
            <u-radio
              :customStyle="{ marginBottom: '8px' }"
              :key="index"
              :name="item.name"
            >
            </u-radio>
          </view>
        </u-radio-group>
        <!--支付方式end-->
        <view class="" style="margin-top: 50rpx">
          <u-button
            text="订单创建中"
            type="primary"
            shape="circle"
            loading
            v-if="isPay"
          ></u-button>

          <u-button
            text="确认选择支付"
            type="primary"
            shape="circle"
            v-else
            @tap.stop="onMultClick(createClock)"
          ></u-button>
        </view>
      </view>
    </u-popup>

    <zPay
      ref="pay"
      :money="pay_money"
      :balance="balance"
      @pay="pay"
      @closePay="closePay"
    ></zPay>
  </view>
</template>

<script>
import zPay from "@/components/z-pay/index.vue";
// import { pay } from '@/config/utils'
import { blancePay, payOrder } from "@/utils/index.js";
export default {
  data() {
    return {
      selectIndex: 0,
      popupshow: false,
      teps: 1, //步骤
      order_sn: "",
      id: 12,
      pay_money: "",
      order_status: 0,
      appointment_time: "",
      fare: "",
      discount: "",
      refund: null,
      total_money: "",
      create_time: "",
      name: "",
      duration: 60,
      cover: "",
      nickname: "",
      realname: "",
      praise: 0,
      avatar: "",
      end_t: "",
      balance: 0,
      clock_num: 0,
      clock_duration: 0,
      technician_mobile: "",
      mobiles: "",
      lockData: [],
      clock_id: 0,
      pay_form: "order",
      clockOrder: 0,
      payList: [],
      payType: "",
      user_realname: "",
      user_mobile: "",
      province: "",
      city: "",
      district: "",
      address: "",
      addrname: "",
      user: "",
      isPay: false,
      trip: {},
      onClick: true,
    };
  },
  onLoad(options) {
    this.payList = [
      {
        name: "账户余额",
      },
      {
        name: "微信支付",
      },
    ];
    let { order_sn } = options;
    this.order_sn = order_sn;
    // this.getWx();
    this.init();
    this.getUserinfo();
  },
  onShow() {
    const sn = uni.getStorageSync("recharge_sn");
    if (sn) {
      this.count = 3;
      this.checkOrderStatus(sn, this.pay_form);
    }
  },
  components: {
    zPay,
  },
  methods: {
    async checkOrderStatus(order_sn, form) {
      const res = await this.$http.post("api/wxapp/check_order_status", {
        order_sn,
        form,
      });
      if (res.code === 1) {
        // 支付成功了
        uni.removeStorageSync("recharge_sn");
        clearTimeout(this.order_time);
        // 跳转到 成功页面
        uni.redirectTo({
          url: "/bundle/pages/pay_success/pay_success",
        });
        return;
      }
      clearTimeout(this.order_time);
      uni.removeStorageSync("recharge_sn");
    },
    getUserinfo() {
      this.$http.post("api/user/userInfo").then((res) => {
        this.user = res;
      });
    },
    closePay() {
      this.cancelClock();
    },
    cancelClock() {
      if (this.pay_form == "clock") {
        this.$http
          .post("api/order/cancelClock", {
            order_sn: this.clockOrder,
          })
          .then((res) => {
            uni.showToast({
              icon: "none",
              title: "加钟取消",
            });
          });
      }
    },
    async createClock() {
      this.isPay = true;
      if (!this.payType) {
        uni.showToast({
          icon: "none",
          title: "请选择支付方式",
        });
        this.isPay = false;
        return;
      }
      if (
        this.payType === "账户余额" &&
        this.lockData[this.selectIndex].price > Number(this.user.balance)
      ) {
        uni.showToast({
          icon: "none",
          title: "账户余额不足",
        });
        this.isPay = false;
        return;
      }
      this.pay_money = this.lockData[this.selectIndex].price;
      let order_info = uni.getStorageSync("order_info");
      order_info.pay_money = this.pay_money;
      uni.setStorageSync("order_info", order_info);
      this.pay_form = "clock";
      await this.$http
        .post("api/order/newCreateClock", {
          order_sn: this.order_sn,
          spec_id: this.lockData[this.selectIndex].id,
        })
        .then((res) => {
          this.clockOrder = res;
        })
        .catch((err) => {
          this.isPay = false;
          die;
        });
      let pay_way =
        this.payType === "账户余额" ? 1 : this.payType === "微信支付" ? 2 : 3;
      if (pay_way !== 1) {
        this.wxPay(this.clockOrder);
      } else {
        await this.$http
          .post("api/pay/pay", {
            order_sn: this.clockOrder,
            pay_way,
            form: this.pay_form,
          })
          .then((res) => {
            uni.navigateTo({
              url: "/bundle/pages/pay_success/pay_success",
            });
            this.isPay = false;
          })
          .catch((err) => {
            this.isPay = false;
            this.$http.post("api/order/cancelClock", {
              order_sn: this.clockOrder,
            });
          });
      }
    },
    selectTime(index, item) {
      this.selectIndex = index;
      this.clock_id = item.id;
    },
    async init() {
      // 获取客服信息 api/user/customerService
      let location = uni.getStorageSync("location");
      if (location) {
        location = JSON.parse(location);
      } else {
        location = { lat: 0, lng: 0 };
      }
      this.$http
        .post(
          `api/user/customerService?lat=${location.lat}&lng=${location.lng}`
        )
        .then((res) => {
          let { mobile } = res;
          this.mobiles = mobile;
        });

      // 获取余额
      this.$http.post("api/user/userInfo").then((res) => {
        this.balance = res.balance;
      });

      let data = await this.$http.post("api/order/orderDetails", {
        order_sn: this.order_sn,
      });

      for (let i in data) {
        this[i] = data[i];
      }
      switch (this.order_status) {
        case 0: //待支付
          this.teps = 1;
          break;
        case 1: //已支付，待接单
          this.teps = 1;
          break;
        case 2: //已接单，待服务
          {
            this.teps = 2;
            if (this.istart == 1) {
              this.teps = 3;
            }
            if (this.arrive == 1) {
              this.teps = 4;
            }
          }
          break;
        case 8: //出发
          this.teps = 3;
          break;
        case 9: //到达
          this.teps = 4;
          break;
        case 3: //服务进行中
          this.teps = 5;
          break;
        default:
          this.teps = 6;
          break;
      }
    },
    call() {
      if (this.middleNumber) {
        uni.makePhoneCall({
          phoneNumber: this.middleNumber + "",
        });
        return;
      }
      uni.showToast({
        icon: "none",
        title: "该技师无号码",
      });
    },
    addtime(e) {
      const order_sn = this.order_sn;
      uni.navigateTo({
        url: `/pages/order/add?ordid=${order_sn}&tab=${e}`,
      });
    },
    calltel() {
      if (this.mobiles) {
        uni.showModal({
          content: "是否拨打客服电话",
          success: (res) => {
            if (res.confirm) {
              uni.makePhoneCall({
                phoneNumber: this.mobiles + "",
              });
            }
          },
        });
        return;
      }
      uni.showToast({
        icon: "none",
        title: "暂无客服联系号码",
      });
    },
    add0(a) {
      a = Number(a);
      return a < 10 ? "0" + a : a;
    },
    showtime(endtime) {
      var nowtime = new Date(), //获取当前时间
        endtime = new Date(endtime.replace(/-/g, "/")); //定义结束时间
      var lefttime = endtime.getTime() - nowtime.getTime(), //距离结束时间的毫秒数
        leftd = Math.floor(lefttime / (1000 * 60 * 60 * 24)), //计算天数
        lefth = Math.floor((lefttime / (1000 * 60 * 60)) % 24), //计算小时数
        leftm = Math.floor((lefttime / (1000 * 60)) % 60), //计算分钟数
        lefts = Math.floor((lefttime / 1000) % 60); //计算秒数
      if (lefttime <= 0) {
        return "已过期";
      }
      return (
        this.add0(leftd) +
        "天" +
        this.add0(lefth) +
        ":" +
        this.add0(leftm) +
        ":" +
        this.add0(lefts)
      ); //返回倒计时的字符串
    },
    hide() {
      uni.showModal({
        content: "是否确认取消该订单？",
        success: (res) => {
          let { confirm } = res;
          if (confirm) {
            this.$http
              .post("api/order/cancelOrder", {
                order_sn: this.order_sn,
              })
              .then((res) => {
                uni.showToast({
                  icon: "none",
                  title: "取消成功",
                });
                this.init();
              });
          }
        },
      });
    },
    getWx() {},
    wxPay(order_sn) {},
    completeOrder(order_sn) {
      var that = this;
      uni.showModal({
        title: "提示",
        content: "是否确认提交完成?",
        confirmText: "确认",
        complete(e) {
          if (e.confirm) {
            uni.showLoading({
              mask: true,
            });
            let options = {
              url: `${that.$base.baseUrl}api/order/completeOrder`,
              data: { order_sn },
              header: {},
              success(res) {
                uni.showToast({
                  title: res.data.msg,
                  icon: "none",
                });
              },
              complete() {
                uni.hideLoading();
                that.init();
              },
            };
            let storeUserInfo = uni.getStorageSync("userInfo");
            if (storeUserInfo.token) {
              options.header.token = storeUserInfo.token;
            }
            uni.request(options);
          }
        },
      });
    },
    show() {
      this.$refs.pay.showPopup = true;
    },
    fill(a) {
      return 10 > a ? "0" + (0 | a) : a;
    },
    async pay(e) {
      let { pay_way, pay_type } = e;
      if (pay_way === 1 && this.pay_money > Number(this.user.balance)) {
        uni.showToast({
          icon: "none",
          title: "账户余额不足",
        });
        this.isPay = false;
        return;
      }

      var order_sn;
      if (this.pay_form == "clock") {
        order_sn = this.clockOrder;
      } else {
        order_sn = this.order_sn;
      }

      let date = new Date();
      let create_time =
        date.getFullYear() +
        "-" +
        this.fill(Number(date.getMonth()) + 1) +
        "-" +
        this.fill(date.getDate()) +
        this.fill(date.getHours()) +
        ":" +
        this.fill(date.getMinutes()) +
        ":" +
        this.fill(date.getDate());

      uni.setStorageSync("order_info", {
        create_time,
        order_sn: order_sn,
        pay_type,
        pay_money: this.pay_money,
      });

      if (pay_way == 1) {
        // 余额支付
        uni.showLoading({
          title: "支付中...",
        });
        blancePay({
          order_sn,
          pay_way,
          form: "order",
        });
      } else {
        // 小程序付款
        this.pay_form = "order";
        uni.setStorageSync("recharge_sn", order_sn);
        // console.log(order_sn, pay_way, this.pay_form);
        this.$http
          .post("api/pay/pay", { order_sn, pay_way, form: this.pay_form })
          .then((res) => {
            console.log("res", res);
            plus.runtime.openURL(res.url_link);
          });
      }
    },
  },
};
</script>

<style scoped lang="scss">
@import "index.scss";
</style>
